import { BodyType, MailMessage, MessageDisposition } from '../model/mail_message'
import { SoapXmlWriter } from '../xml/soap_xml'
import { FolderName, XmlAttribute } from '../xml/xml_attribute';
import { XmlElement } from '../xml/xml_element';
import { XmlNamespace } from '../xml/xml_namespace';
import { RequestBase } from './request_base'

export class SendMailRequest extends RequestBase<MailMessage> {
  protected writeHeaderToXml(soapXmlWriter: SoapXmlWriter) {
    this.writeCommonHeader(soapXmlWriter);
  }

  protected writeBodyToXml(soapXmlWriter: SoapXmlWriter) {
    soapXmlWriter.writeStartElement(XmlNamespace.SOAP, XmlElement.NAME_BODY);
    soapXmlWriter.writeStartElement(XmlNamespace.MESSAGE, XmlElement.NAME_CREATE_ITEM);

    soapXmlWriter.writeAttribute(XmlAttribute.NAME_MESSAGE_DISPOSITION, MessageDisposition[this.rawData.getMessageDisposition()]);
    soapXmlWriter.writeStartElement(XmlNamespace.MESSAGE, XmlElement.NAME_SAVED_ITEM_FOLDER_ID)
      .writeElementWithAttribute(XmlNamespace.TYPE, XmlElement.NAME_DISTINGUISHED_FOLDER_ID,
        new Map([[XmlAttribute.NAME_ID, FolderName[this.rawData.getFolderName()]]]))
      .writeEndElement();

    soapXmlWriter.writeStartElement(XmlNamespace.MESSAGE, XmlElement.NAME_ITEMS);
    soapXmlWriter.writeStartElement(XmlNamespace.TYPE, XmlElement.NAME_MESSAGE);
    let message = this.rawData.getMessage();
    soapXmlWriter.writeElementWithValue(XmlNamespace.TYPE, XmlElement.NAME_SUBJECT, message.subject);
    soapXmlWriter.writeIntactElement(XmlNamespace.TYPE, XmlElement.NAME_BODY, new Map([[XmlAttribute.NAME_BODYTYPE, FolderName[BodyType[message.bodyType]]]]), message.body);

    soapXmlWriter.writeStartElement(XmlNamespace.TYPE, XmlElement.NAME_TORECIPIENTS);
    soapXmlWriter.writeStartElement(XmlNamespace.TYPE, XmlElement.NAME_MAILBOX);
    for (const address of message.emailAddress) {
      soapXmlWriter.writeElementWithValue(XmlNamespace.TYPE, XmlElement.NAME_EMAILADDRESS, address);
    }
    soapXmlWriter.writeEndElement();
    soapXmlWriter.writeEndElement();

    soapXmlWriter.writeEndElement();
    soapXmlWriter.writeEndElement();

    soapXmlWriter.writeEndElement();
    soapXmlWriter.writeEndElement();
  }
}